package ccxz.biz.controller;

import ccxz.biz.SetupApplication;
import ccxz.biz.application.dto.ExcelImportVO;
import ccxz.biz.application.service.BizApplicationService;
import ccxz.biz.application.util.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import de.felixroske.jfxsupport.FXMLController;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.stage.FileChooser;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ResourceBundle;

@FXMLController
public class HomeController implements Initializable {
    @Autowired
    BizApplicationService bizApplicationService;

    @FXML
    private Button uploadButton;

    private final static String PATH = "/固真堂";

    /**
     * 登陆
     */
    @FXML
    public void uploadFile() {
        File desktopPath = new File(System.getProperty("user.home") + "/Desktop");
        FileChooser fileChooser = new FileChooser();
        fileChooser.setInitialDirectory(desktopPath);
        //设置文件上传类型
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("excel files (*.xlsx)", "*.xlsx");
        fileChooser.getExtensionFilters().add(extFilter);
        File file = fileChooser.showOpenDialog(uploadButton.getScene().getWindow());
        System.out.println("你选择的文件路径为：" + file.getPath());

        this.handleExcel(file.getPath());

        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText("数据处理完成");
        alert.setContentText("点击是打开文件系统查看处方单");
        ButtonType buttonTypeYes = new ButtonType("是");
        ButtonType buttonTypeNo = new ButtonType("否");
        alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeNo);
        alert.showAndWait().ifPresent(buttonType -> {
            if (buttonType == buttonTypeYes) {
                LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
                String path = desktopPath.getAbsolutePath() + PATH + DateUtil.format(yesterday, "yyyy-MM-dd");
                System.out.println(path);
                openFileLocation(path);
            } else if (buttonType == buttonTypeNo) {
                System.out.println("仅关闭");
            }
        });
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        SetupApplication.controllers.put(this.getClass().getSimpleName(), this);
    }


    public void handleExcel(String fileName) {

        EasyExcel.read(fileName, ExcelImportVO.class, new ReadListener<ExcelImportVO>() {

            @Override
            public void invoke(ExcelImportVO data, AnalysisContext context) {
                LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
                File logFile = new File(System.getProperty("user.home") + "/Desktop" + PATH + DateUtil.format(yesterday, "yyyy-MM-dd") + "/log.txt");
                try {
                    bizApplicationService.handle(data, PATH + DateUtil.format(yesterday, "yyyy-MM-dd"));
                    FileUtils.write(logFile, data.getOrderId() + " 成功\n", "UTF-8", true);
                } catch (Exception e) {
                    try {
                        FileUtils.write(logFile, data.getOrderId() + "失败\n", "UTF-8", true);
                    } catch (IOException ex) {
                    }
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {

            }
        }).sheet().doRead();

    }

    public static void openFileLocation(String path) {
        try {
            Runtime.getRuntime().exec("explorer.exe /select," + path);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
